package com.usian.comment.service.Impl;

import com.usian.comment.feign.ApUserFeign;
import com.usian.comment.service.ApCommentService;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.pojos.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ApCommentServiceImp implements ApCommentService {
    @Autowired
    private ApUserFeign apUserFeign;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //远程调用获取作者姓名
        ApUser apUser = apUserFeign.findUserById(user.getId());

        //mongo中保存评论
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.insert(apComment);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /***
     * 点赞取消点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment != null && dto.getOperation() == 0) {
            //点赞 update apcomment  的like字段+1 ApCommentLike添加
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
            //保存 APP评论信息点赞
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);

        } else if (apComment != null && dto.getOperation() == 1) {
            //取消点赞apcomment  的like字段-1 ApCommentLike 表删除
            apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            Query query = new Query().addCriteria(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("likes", apComment.getLikes());
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1:校验参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2:根据文章id查询评论列表
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId())
                .and("createdTime").lt(dto.getMinDate())).limit(10).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

        //3:如果登录的话 过滤登录的用户都点赞过哪些评论

        //获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        List<ApCommentVo> resultList = new ArrayList<>();
        if (resultList != null && apCommentLikes != null) {
            resultList.stream().forEach(x -> {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(x, apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (x.getId().equals(apCommentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                        break;
                    }
                }
                resultList.add(apCommentVo);
            });
            return ResponseResult.okResult(resultList);
        } else {
            return ResponseResult.okResult(list);
        }
    }
}
